<?php
class ChartInfo extends CI_Model {
    public function __construct()
    {
            $this->load->database();
    }
    public function get_info($week=0,$question=0)
    {
        if($week>0&&$question>0){
            $condition = array(
                'ques' => $question,
                'week' => $week
            );
            //$query=$this->db->where($condition)->select('ans,count')->get('chartinfo');
            $query=$this->db->where($condition)->select('label,count')->order_by('ans','asc')->get('chartinfo')->result_array();
            $result=array("title"=>array(),"value"=>array());
            foreach($query as $item){
                $result["title"][]="'".$item["label"]."'";
                $result["value"][]=$item["count"];
            }
            return $result;
        }
        return NULL;
    }
    public function add_response($answerlist, $week = 0, $question = 0){
        if($week>0&&$question>0&&$this->input->post('question-group-'.$week)>0){
            
            $condition = array(
                'ques' => $question,
                'ans' => $this->input->post('question-group-'.$week),
                'week' => $week
            );
            
            $query=$this->db->where($condition)->select('count')->get('chartinfo');
            
            if($query->num_rows() == 0){
                /* check if data was emty, app will insert a row automatically*/
                $label=NULL;
                echo 'label <br>';
                foreach($answerlist as $item){
                    echo $item['code'].' '.intval($this->input->post('question-group-'.$week));
                    if($item["code"]==intval($this->input->post('question-group-'.$week))){
                        $label=$item["title"];
                        break;
                    }
                }
                $data = array(
                    'ques'  =>  $question,
                    'ans'   =>  $this->input->post('question-group-'.$week),
                    'week'  =>  $week,
                    'label' =>  $label
                );
                $this->db->insert('chartinfo',$data);
                $query=$this->db->where($condition)->select('count')->get('chartinfo');
            }
            
            $result=$query->row()->count;
            $this->db->where($condition)->update('chartinfo',array('count'=>$result+1));
            
            $query=$this->db->where($condition)->select('count')->get('chartinfo');
            $result=$query->row()->count;
            return $result;
        }
        return 0;
    }
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
?>
